/**
 * Created with JetBrains WebStorm.
 * User: Administrator
 * Date: 14-6-13
 * Time: 下午3:57
 * To change this template use File | Settings | File Templates.
 */
define(function(require,exports,module){
    var VERSION = '1.0',
        jQuery = $ = require("jquery-1.8.2.min");

    var defaults = {
        'data':{},
        'tabs':'',
        'defaultText':'输入平台名称/拼音',
        'popTitleText':'请选择平台或输入平台名称的拼音或英文',
        'suggestTitleText':"输入中文/拼音或↑↓选择",
        'suggestLength':10,
        'pageLength':5,
        'onSelect':5
    };

    function queryP2P(element,options){
        this.$elem = $(element);
        this.options = $.extend(true,{},defaults,options);
        this.init();
    }

    queryP2P.prototype = {
        init:function(){
            var that = this,
                input = this.$elem,
                options = this.options;

            var tmpl1 = "<div id='pop_city_"+input.attr('id')+"' class='pop_city' style='display:none'>" +
                        "<p class='pop_head'></p>" +
                        "<ul class='list_label'></ul>" +
                        "<div class='pop_city_container'></div>" +
                        "</div>";

            var tmpl2 = "<div id='suggest_city_"+input.attr('id')+"' " +
                "class='list_city' style='display:none'>" +
                "<div class='list_city_head'></div>" +
                "<div class='list_city_container'></div>" +
                "<div class='page_break'></div>" +
                "</div>";

            $("body").append(tmpl1).append(tmpl2);

            this.$elem.attr("autocomplete","off");

            var popMain,popContainer,labelMain,suggestMain;
            popMain = this.popMain = $("#pop_city_"+input.attr('id'));
            popContainer = this.popContainer = popMain.find('.pop_city_container');
            labelMain = this.labelMain = popMain.find('.list_label');
            suggestMain = this.suggestMain = $("#suggest_city_"+input.attr('id'));

            var t_pop_focus = false;
            var t_suggest_focus = false;
            var t_suggest_page_click = false;

            this.popInit();
            this.resetPosition();

           input.focus(function(){
               if(t_suggest_page_click){
                   t_suggest_page_click = false;
                   return true;
               }
               suggestMain.hide();
               popMain.show();
           }).click(function(){
               if(t_suggest_page_click){
                   t_suggest_page_click = false;
                   return;
               }
               suggestMain.hide();
               popMain.show();
           }).blur(function(){
               if(t_pop_focus == false){
                   popMain.hide();
               }
           });

           labelMain.find('a').live('click',function(){
               input.focus();
               t_pop_focus = true;
               var labelId = $(this).attr("id");
               labelMain.find("li a").removeClass('current');
               $(this).addClass('current');
               popContainer.find("ul").hide();
               $("#"+labelId+"_container").show();
           });

           popContainer.find("a").live('click',function(){
               input.val($(this).html());
               popMain.hide();
           });

           popMain.mouseover(function(){
               t_pop_focus = true;
           }).mouseout(function(){
               t_pop_focus = false;
           });

           input.blur(function(){
               if(t_suggest_focus == false){
                   if($(this).val() == ''){
                       $(this).val(suggestMain.find(".list_city_container a.selected").children('b').text());
                   }
                   suggestMain.hide();
               }
           }).keydown(function(event){
                   popMain.hide();
                   event = window.event || event;
                   var keyCode = event.keyCode || event.which || event.charCode;
                   if(keyCode == 37){
                       that.prevPage();
                   }else if(keyCode == 39){
                       that.nextPage();
                   }else if(keyCode == 38){
                       that.prevResult();
                   }else if(keyCode == 40){
                       that.nextResult();
                   }
               }).keypress(function(event){
                   event = window.event || event;
                   var keyCode = event.keyCode || event.which || event.charCode;
                   if(13 == keyCode){
                       if(suggestMain.find('.list_city_container a.selected').length > 0){
                           input.val(suggestMain.find('.list_city_container a.selected').children('b').text());
                           suggestMain.hide();
                       }
                   }
               }).keyup(function(event){
                   event = window.event || event;
                   var keyCode = event.keyCode || event.which || event.charCode;
                   if(keyCode != 13 && keyCode != 37 && keyCode != 39 && keyCode !=9 && keyCode !=38 && keyCode !=40 ){
                       //keyCode == 9是tab切换键
                       that.queryP2P();
                   }
               });

            suggestMain.find('.list_city_container a').live('click',function(){
                input.val($(this).children('b').text());
                suggestMain.hide();
            }).live('mouseover',function(){
                    t_suggest_focus = true;
                }).live('mouseout',function(){
                    t_suggest_focus = false;
                });
            suggestMain.find('.page_break a').live('mouseover',function(){
                t_suggest_focus = true;
            }).live('mouseout',function(){
                    t_suggest_focus = false;
                });
            suggestMain.find('.page_break a').live('click',function(event){
                t_suggest_page_click = true;
                input.click();
                if($(this).attr('inum') != null){
                    that.setAddPage($(this).attr('inum'));
                }
            });
        },
        nextPage:function(){
            var suggestMain = this.suggestMain;
            var add_cur = suggestMain.find(".page_break a.current").next();
            if(add_cur !=null){
                if($(add_cur).attr("inum")!=null){
                    this.setAddPage($(add_cur).attr('inum'))
                }
            }
        },
        prevPage:function(){
            var add_cur = this.suggestMain.find(".page_break a.current").prev();
            if(add_cur != null){
                if($(add_cur).attr("inum") != null){
                    this.setAddPage($(add_cur).attr("inum"));
                }
            }
        },
        nextResult:function(){
            var suggestMain = this.suggestMain;
            var t_index = suggestMain.find('.list_city_container a').index(suggestMain.find(".list_city_container a.selected")[0]);
            suggestMain.find(".list_city_container").children().removeClass('selected');
            t_index +=1;
            var t_end = suggestMain.find('.list_city_container a').index(suggestMain.find(".list_city_container a:visible").eq(0));

            if(t_index > t_end){
                t_index = suggestMain.find(".list_city_container a").index(suggestMain.find(".list_city_container a:visible").eq(0));
            }
            suggestMain.find(".list_city_container a").eq(t_index).addClass('selected');
        },
        prevResult:function(){
            var suggestMain = this.suggestMain;
            var t_index = suggestMain.find('.list_city_container a').index(suggestMain.find('.list_city_container a.selected')[0]);
            suggestMain.find('.list_city_container').children().removeClass('selected');
            t_index -= 1;
            var t_start = suggestMain.find('.list_city_container a').index(suggestMain.find('.list_city_container a:visible').filter(':first')[0]);
            if( t_index < t_start){
                t_index = suggestMain.find('.list_city_container a').index(suggestMain.find('.list_city_container a:visible').filter(':last')[0]);
            }
            suggestMain.find('.list_city_container a').eq(t_index).addClass('selected');
        },
        loadCity:function(){
            var suggestMain = this.suggestMain,
                options = this.options;
            var cityList = suggestMain.find('.list_city_container');
            cityList.empty();
            if(options.hotList){
                var hotList = options.hotList;
            }else{
                var hotList = [0,1,2,3,4,5,6,7,8,9];
            }
            for(var item in hotList){
                if(item>options.suggestLength){
                    return;
                }
                var _data = options.data[hotList[item]];
                cityList.append("<a href='javascript:void(0)' ><span>"+_data[2]+"</span><b>"+_data[1]+"</b></a>");
            }
            suggestMain.find('.list_city_head').html(options.suggestTitleText);
            this.setAddPage(1);
            suggestMain.show();
            this.setTopSelect();
        },
        queryP2P:function(){
            var input = this.$elem,
                popMain = this.popMain,
                suggestMain = this.suggestMain,
                options = this.options;

            popMain.hide();
            var value = input.val().toLowerCase();
            if( value.length == 0){
                this.loadCity();
                return;
            }
            var city_container = suggestMain.find('.list_city_container');
            var isHave = false;
            var _tmp = new Array();
            for(var item in options.data){
                var _data = options.data[item];
                if(typeof (_data) != 'undefined'){
                    if(_data[2].indexOf(value) >= 0 || _data[1].indexOf(value) >=0 || _data[0].indexOf(value) >=0 ){
                        isHave = true;
                        _tmp.push(_data);
                    }
                }
            }
            if(isHave){
                city_container.empty();
                for(var item in _tmp){
                    var _data= _tmp[item];
                    city_container.append("<a href='javascript:void(0)' style='display:none'><span>"+_data[1]+"</span><b>"+     _data[0] +"</b></a>");
                }
                suggestMain.find('.list_city_head').html(value+",按拼音排序");
                this.setAddPage(1);
                this.setTopSelect()
            }else{
                suggestMain.find('.list_city_head').html("<span class='msg'>对不起,找不到"+value+"</span>");
            }
            suggestMain.show();
        },
        setAddPage:function(pageIndex){
            var options = this.options,
                suggestMain = this.suggestMain;
            suggestMain.find('.list_city_container a').removeClass('selected');
            suggestMain.find('.list_city_container').children().each(function(i){
                var k = i+1;
                if(k> options.suggestLength*(pageIndex-1) && k <= options.suggestLength*pageIndex){
                    $(this).css('display','block');
                }else{
                    $(this).hide();
                }
            });
            this.setTopSelect();
            this.setAddPageHtml(pageIndex);
        },
        setAddPageHtml:function(pageIndex){
            var options = this.options,
                suggestMain = this.suggestMain;
            var cityPageBreak = suggestMain.find('.page_break');
            cityPageBreak.empty();
            if(suggestMain.find('.list_city_container').children().length > options.suggestLength){
                var pageBreakSize = Math.ceil(suggestMain.find('.list_city_container').children().length/options.suggestLength);
                if(pageBreakSize <= 1){
                    return;
                }
                var start = end = pageIndex;
                for(var index = 0 ,num = 1 ; index < options.pageLength && num < options.pageLength; index++){
                    if(start > 1){
                        start--;num++;
                    }
                    if(end<pageBreakSize){
                        end ++;num++;
                    }
                }
                if(pageIndex > 1){
                    cityPageBreak.append("<a href='javascript:void(0)' inum='"+(pageIndex-1)+"'>&lt;-</a>");
                }
                for(var i=start;i<=end;i++){
                    if(i == pageIndex){
                        cityPageBreak.append("<a href='javascript:void(0)' class='current' inum='"+(i)+"'>"+(i)+"</a");
                    }else{
                        cityPageBreak.append("<a href='javascript:void(0)' inum='"+(i)+"'>"+(i)+"</a");
                    }
                }
                if (pageIndex<pageBreakSize) {
                    cityPageBreak.append("<a href='javascript:void(0);' inum='"+ (i) +"'>-&gt;</a>");
                }
                cityPageBreak.show();
            }else{
                cityPageBreak.hide();
            }
            return;
        },
        setTopSelect:function(){
            var suggestMain = this.suggestMain;
            if(suggestMain.find('.list_city_container').children().length > 0 ){
                suggestMain.find('.list_city_container').children(':visible').eq(0).addClass('selected');
            }
        },
        onSelect:function(){
            var options = this.options;
            if( typeof options.onSelect == 'function'){
                alert(1);
            }
        },
        popInit:function(){
            var popMain = this.popMain,
                options = this.options,
                popContainer = this.popContainer,
                input = this.$elem,
                labelMain = this.labelMain;

            var index = 0;
            popMain.find('.pop_head').html(options.popTitleText);

            if(!options.tabs){
                popContainer.append("<ul id='label_"+input.attr('id')+"_container' class='current'></ul>");
                labelMain.remove();
                for( var item in options.data){
                    $("#label_"+input.attr('id')+"_container").append("<li><a href='javascript:void(0)'>"+options.data[item][1]+"</a></li>");
                }
                return;
            }
            for(var itemLabel in options.tabs){
                index++;
                if(index == 1){
                    popContainer.append("<ul id='label_"+input.attr('id')+index+"_container' class='current' data-type='"+itemLabel+"'></ul>");
                    labelMain.append("<li><a id='label_"+input.attr('id')+index+"' class='current' href='javascript:void(0)'>"+itemLabel+"</a></li>");
                }else{
                    popContainer.append("<ul style='display:none' id='label_"+input.attr('id')+index+"_container' data-type='"+itemLabel+"'></ul>");
                    labelMain.append("<li><a id='label_"+input.attr('id')+index+"' href='javascript:void(0)'>"+itemLabel+"</a></li>");
                }
                for(var item in options.tabs[itemLabel]){
                    var cityCode = options.tabs[itemLabel][item];
                    if(!options.data[cityCode]){
                        break;
                    }
                    $("#label_"+input.attr('id')+index+"_container").append("<li><a href='javascript:void(0)'>"+options.data[cityCode][0]+"</a></li>");
                }
            }
        },
        resetPosition:function(){
            var input = this.$elem,
                popMain = this.popMain,
                suggestMain = this.suggestMain;

            popMain.css({'top':input.offset().top+input.outerHeight(),'left':input.offset().left-1});
            suggestMain.css({'top':input.offset().top+input.outerHeight(),'left':input.offset().left});
        }
    };

    return queryP2P;
});